﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

namespace Transport
{
    class ChiTietDatXeControl
    {
        transportEntities db;

        public ChiTietDatXeControl()
        {
            db = new transportEntities();
        }

        public chi_tiet_dat_xe findById(string id)
        {
            try
            {
                return db.chi_tiet_dat_xe.SingleOrDefault(t => t.id == id);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public List<chi_tiet_dat_xe> findByUsername(string username)
        {
            try
            {
                return db.chi_tiet_dat_xe.Where(t => t.ten_dang_nhap == username).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public string insertTheoTour(chi_tiet_dat_xe value)
        {
            try
            {
                LoTrinhControl lt = new LoTrinhControl();

                value.ngay_dat = DateTime.Now;
                value.ma_dich_vu = "0";
                value.ma_tinh_trang_dat_xe = "1";
                value.phuong_thuc_lai = "1";
                value.chi_phi_du_kien = 0;

                string mamien = lt.getRegionID(value.ma_lo_trinh);
                if (mamien != "")
                    value.ma_mien = mamien;
                else
                    value.ma_mien = "0";

                bool flag = insert(value);



                if (flag == true)
                    return value.id;
                else
                    return "false";
            }
            catch (Exception)
            {
                return "false";
            }
        }

        public string insertTheoYeuCau(chi_tiet_dat_xe value)
        {
            try
            {
                value.ngay_dat = DateTime.Now;
                value.ma_tinh_trang_dat_xe = "1";
                value.ma_lo_trinh = "0";
                value.chi_phi_du_kien = 0;

                bool flag = insert(value);

                if (flag == true)
                    return value.id;
                else
                    return "false";
            }
            catch (Exception)
            {
                return "false";
            }
        }

        public bool insert(chi_tiet_dat_xe value)
        {
            try
            {
                GiamGiaControl ggCtrl = new GiamGiaControl();
                NguoiDungControl ndCtrl = new NguoiDungControl();
                DateTime centuryBegin = new DateTime(2000, 1, 1);
                DateTime currentDate = DateTime.Now;
                
                value.id = (currentDate.Ticks - centuryBegin.Ticks).ToString();
                value.ti_le_giam_gia = ggCtrl.findByUserName(value.ten_dang_nhap);

                db.chi_tiet_dat_xe.AddObject(value);
                db.SaveChanges();

                Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
                MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

                String fromEmail = mailSettings.Smtp.Network.UserName;
                String toEmail = ndCtrl.getEmail(value.ten_dang_nhap);
                string host = mailSettings.Smtp.Network.Host;
                int port = mailSettings.Smtp.Network.Port;
                string password = mailSettings.Smtp.Network.Password;
                MailMessage message = new MailMessage(fromEmail, toEmail);
                message.Subject = "[HKTransport] Đặt xe";
                message.Body = "Kính chào quý khách,\nQuý khách đã đặt xe thành công. Mã số đặt xe của quý khách là: " + value.id + "\nChúng tôi rất hân hạnh được phục vụ quý khách.\nTrung tâm hỗ trợ HK Transport";

                SmtpClient smtp = new SmtpClient(host, port);
                smtp.EnableSsl = true;
                smtp.Credentials = new NetworkCredential(fromEmail, password);
                smtp.Send(message);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool update(chi_tiet_dat_xe value)
        {
            try
            {
                chi_tiet_dat_xe ct = db.chi_tiet_dat_xe.SingleOrDefault(t => t.id == value.id);
                ct = value;
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool updateReservationStatus(string ID, string StatusID)
        {
            try
            {
                chi_tiet_dat_xe ct = db.chi_tiet_dat_xe.SingleOrDefault(t => t.id == ID);
                ct.ma_tinh_trang_dat_xe = StatusID;
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool updatePhiDuKien(string ID, int fee)
        {
            try
            {
                chi_tiet_dat_xe ct = db.chi_tiet_dat_xe.SingleOrDefault(t => t.id == ID);
                ct.chi_phi_du_kien = fee;
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool updateTienDaThanhToan(string ID, int fee)
        {
            try
            {
                chi_tiet_dat_xe ct = db.chi_tiet_dat_xe.SingleOrDefault(t => t.id == ID);
                ct.tien_da_thanh_toan = fee;
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool delete(string Id)
        {
            try
            {
                chi_tiet_dat_xe ct = db.chi_tiet_dat_xe.SingleOrDefault(t => t.id == Id);
                db.chi_tiet_dat_xe.DeleteObject(ct);
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public int calculateFee(chi_tiet_dat_xe value)
        {
            DanhSachXeDatControl ctxdCtrl = new DanhSachXeDatControl();
            List<danh_sach_xe_dat> list = ctxdCtrl.findByReservationID(value.id);

            int total = 0;

            //Lo trinh dinh san
            if (value.ma_dich_vu == "0")
            {
                BangGiaLoTrinhAdminControl ctrl1 = new BangGiaLoTrinhAdminControl();

                for (int i = 0; i < list.Count; i++)
                {
                    bang_gia_theo_lo_trinh item = ctrl1.findByCarNumberAndRouteID(list[i].bien_so, value.ma_lo_trinh);

                    total += item.gia_tien;
                }
            }
            //Xe cuoi
            else if (value.ma_dich_vu == "1")
            {
                BangGiaNgayAdminControl ctrl2 = new BangGiaNgayAdminControl();

                for (int i = 0; i < list.Count; i++)
                {
                    bang_gia_trong_ngay item = ctrl2.findByCarNumberAndServiceID(list[i].bien_so, value.ma_dich_vu);

                    total += item.gia_tien * ((value.den_ngay.Date - value.tu_ngay.Date).Days + 1) + item.gia_trang_tri; 
                }
            }
            //Con lai
            else
            {
                BangGiaNgayAdminControl ctrl3 = new BangGiaNgayAdminControl();

                //Co tai xe hay khong?
                if (value.phuong_thuc_lai == "1")
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        bang_gia_trong_ngay item = ctrl3.findByCarNumberAndServiceID(list[i].bien_so, value.ma_dich_vu);

                        total += (item.gia_tien + item.chi_phi_tai_xe + item.phi_luu_dem) * ((value.den_ngay.Date - value.tu_ngay.Date).Days + 1) - item.phi_luu_dem;
                    }
                }
                else
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        bang_gia_trong_ngay item = ctrl3.findByCarNumberAndServiceID(list[i].bien_so, value.ma_dich_vu);

                        total += (item.gia_tien + item.phi_luu_dem) * ((value.den_ngay.Date - value.tu_ngay.Date).Days + 1) - item.phi_luu_dem;
                    }
                }
            }

            value.chi_phi_du_kien = total - (int)(total * value.ti_le_giam_gia);

            return total;
        }
        public int calculateFeeWithIDCarNSerVice(string IDCar,string IDservice,DateTime tungay,DateTime denngay,int phuongthuclai,string malotrinh)
        {

            int total = 0;

            //Lo trinh dinh san
            if (IDservice == "0")
            {
                BangGiaLoTrinhAdminControl ctrl1 = new BangGiaLoTrinhAdminControl();
                bang_gia_theo_lo_trinh item = ctrl1.findByCarNumberAndRouteID(IDCar, malotrinh);

                total += item.gia_tien;
            }
            //Xe cuoi
            else if (IDservice == "1")
            {
                BangGiaNgayAdminControl ctrl2 = new BangGiaNgayAdminControl();
                bang_gia_trong_ngay item = ctrl2.findByCarNumberAndServiceID(IDCar, IDservice);

                    total += item.gia_tien * ((denngay.Date - tungay.Date).Days + 1) + item.gia_trang_tri;
            }
            //Con lai
            else
            {
                BangGiaNgayAdminControl ctrl3 = new BangGiaNgayAdminControl();

                //Co tai xe hay khong?
                if (phuongthuclai == 1)
                {
                        bang_gia_trong_ngay item = ctrl3.findByCarNumberAndServiceID(IDCar,IDservice);

                        total += (item.gia_tien + item.chi_phi_tai_xe + item.phi_luu_dem) * ((denngay.Date - tungay.Date).Days + 1) - item.phi_luu_dem;
                }
                else
                {
                        bang_gia_trong_ngay item = ctrl3.findByCarNumberAndServiceID(IDCar, IDservice);

                        total += (item.gia_tien + item.phi_luu_dem) * ((denngay.Date - tungay.Date).Days + 1) - item.phi_luu_dem;
                }
            }

            return total;
        }
        public int calculateFee(string id)
        {
            chi_tiet_dat_xe value = findById(id);

            if (value != null)
            {
                calculateFee(value);
                return value.chi_phi_du_kien;
            }

            return 0;
        }

        public int calculateCancelMoney(string id, DateTime date)
        {
            chi_tiet_dat_xe value = findById(id);

            if ((date - value.ngay_dat).Days == 0)
            {
                double num1 = double.Parse(WebConfigurationManager.AppSettings["SauKhiMua"]);
                return (int)(value.chi_phi_du_kien * num1);
            }
            else
            {
                if ((value.tu_ngay - date).Days <= 7)
                {
                    double num2 = double.Parse(WebConfigurationManager.AppSettings["TruocBayNgay"]);
                    return (int)(value.chi_phi_du_kien * num2);
                }
            }

            double num3 = double.Parse(WebConfigurationManager.AppSettings["ConLai"]);
            return (int)(value.chi_phi_du_kien * num3);
        }

        public int calculateTotalDays(chi_tiet_dat_xe value)
        {
            DanhSachXeDatControl ctrl = new DanhSachXeDatControl();
            List<danh_sach_xe_dat> list = ctrl.findByReservationID(value.id);

            value.so_luong_xe = list.Count;

            return value.so_luong_xe;
        }

        public int cancelReservation(string id)
        {
            try
            {
                chi_tiet_dat_xe value = findById(id);
                if (value == null)
                    return -1;
                if (value.ma_tinh_trang_dat_xe == "4") //Da huy
                    return -1;
                
                int fee = calculateFee(id);

                if (fee == 0) //Dat xe qua webservice voi thong tin chung chung, chua duoc dieu xe
                {
                    value.chi_phi_du_kien = 0;
                    value.tien_da_thanh_toan = 0;
                }
                else // Da thanh toan day du voi so tien bang chi_phi_du_kien
                {
                    //Lay thoi gian tu bang huy dat xe. Neu khong co thi chen cai moi vao
                    HuyDatXeControl ctrl = new HuyDatXeControl();
                    huy_dat_xe info = ctrl.findByID(id);
                    DateTime cancelTime = DateTime.Now;
                    if (info != null)
                        cancelTime = info.thoi_gian;
                    else
                    {
                        info = new huy_dat_xe();
                        info.id = value.id;
                        info.thoi_gian = cancelTime;
                        ctrl.insert(info);
                    }

                    value.chi_phi_du_kien = fee;
                    value.tien_da_thanh_toan = calculateCancelMoney(id, cancelTime);       
                }

                value.ma_tinh_trang_dat_xe = "4";
                update(value);

                // Chuyen tien tu dong cho khach 
                // Pending

                // Gui mail

                NguoiDungControl ndCtrl = new NguoiDungControl();
                Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
                MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

                String fromEmail = mailSettings.Smtp.Network.UserName;
                String toEmail = ndCtrl.getEmail(value.ten_dang_nhap);
                string host = mailSettings.Smtp.Network.Host;
                int port = mailSettings.Smtp.Network.Port;
                string password = mailSettings.Smtp.Network.Password;
                MailMessage message = new MailMessage(fromEmail, toEmail);
                message.Subject = "[HKTransport] Hủy đặt xe";
                message.Body = "Kính chào quý khách,\nQuý khách đã hủy đặt xe thành công. Mã số đặt xe đã hủy là: " + value.id + "\nChúng tôi rất hân hạnh được phục vụ quý khách.\nTrung tâm hỗ trợ HK Transport";

                SmtpClient smtp = new SmtpClient(host, port);
                smtp.EnableSsl = true;
                smtp.Credentials = new NetworkCredential(fromEmail, password);
                smtp.Send(message);

                return value.tien_da_thanh_toan - value.chi_phi_du_kien;
            }
            catch (Exception)
            {
                return -1;
            }
        }

        public List<chi_tiet_dat_xe> getListToCancel(string username)
        {
            try
            {
                int intv = int.Parse(WebConfigurationManager.AppSettings["ThoiHanHuy"]);
                return db.chi_tiet_dat_xe.Where(t => t.ten_dang_nhap == username && ((DateTime.Now - t.ngay_dat).Days <= intv) && (DateTime.Now <= t.tu_ngay)).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
